<template>
	<view>
		<view class="cell">
			<view class="cell-left">
				<view class="cell-text">8D单照片上传：</view>
				<view class="cell-text" style="color: #8C8C8C;width: 180px;">(最多上传3张图片)</view>
			</view>
			<view class="cell-left">
				<view class="qtpicker">
					<!-- 选中待上传的图片 -->
					<view class="preImgs" v-for="(val,index) in preImgUrl" :key='index'>
						<image style="border-radius: 6px;" mode="" :src="val" @click="showImg(val,index)">
						</image>
						<view v-show="isShowDelImgBtn"
							v-if="item.afterSales8DForm == null || item.afterSales8DForm == ''">
							<image class="cuo" mode="" src="../../../static/小关闭.png" @click="delImg(index)">
							</image>
						</view>

					</view>
					<view v-show="isShowAddImgBtn" v-if="item.afterSales8DForm == null || item.afterSales8DForm == ''">
						<image style="width: 200rpx;height: 200rpx;margin-left: 13rpx;margin-top: 13rpx;"
							@click="chooseImg" mode="" src="../../../static/添加图片.png">
						</image>
					</view>

				</view>
			</view>

		</view>
		<!-- 确定上传到服务器 -->
		<button :disabled="submitForbide" v-if="item.afterSales8DForm == null || item.afterSales8DForm == ''"
			type="primary" style="width: 50%;margin-top: 40px;" @click="submitImg">确认上传</button>
		<!-- <view style="margin-left: 35%;margin-top: 3px; font-size: 12px;">今日上报：{{completionStatus}}</view> -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				item: [],
				preImgUrl: [], //本地预览的图片数据
				components: [],
				imgNum: 0, //一共选中了多少张照片,用来限制本次最大上传数量
				afterUploadPath: '', //上传图片后，返回上传后的图片地址入库用
				isShowAddImgBtn: true,
				content: '',
				fault_id: '',
				contentText: '',
				addoredit: 'add',
				editclick: 0, //是否点击了右上角的编辑按钮
				faultConfirmId: '',
				isShowDelImgBtn: true,
				submitForbide: false,
				radiobakcolor: '',
				completionStatus: null,
				date: new Date().toISOString(),
			}
		},
		onLoad(option) {
			this.item = JSON.parse(option.item)
			let imgArr = []
			if (this.item.afterSales8DForm != null && this.item.afterSales8DForm != '') {
				let a = this.item.afterSales8DForm.substring(0, this.item.afterSales8DForm.length - 1);
				imgArr = a.split(',')
				this.preImgUrl = imgArr
			}
		},
		methods: {
			// 选择图片
			chooseImg() {
				//如果是之前确认过，但是没点击编辑按钮，则直接return
				if (this.addoredit == 'edit' && this.editclick == 0) {
					return
				}
				let that = this
				uni.chooseImage({
					// count:  允许上传的照片数量
					count: 3, //h5无法限制
					// sizeType:  original 原图，compressed 压缩图，默认二者都有
					sizeType: "original，compressed",
					success: function(res) { //选择成功，将图片存入本地临时路径，可删除，可查看，等待上传
						console.log(res, '选择成功')

						// 如果限制图片大小，则添加判断
						res.tempFiles.map(val => {

							// 判断本次上传限制的图片大小
							if (val.size > 10485760) {
								uni.showToast({
									icon: 'none',
									title: '上传的图片大小不超过10M'
								})
								return
							}

							// 判断本次最多上传多少照片
							that.imgNum++
							if (that.imgNum == 3) {
								that.isShowAddImgBtn = false
								uni.showToast({
									icon: 'none',
									title: '最多上传3张图片'
								})
							}
							if (that.imgNum > 3) {
								that.imgNum = 3
								uni.showToast({
									icon: 'none',
									title: '上传的图片最多不能超过3张'
								})
								return
							}
							//把临时路径添加进数组，渲染到页面
							that.preImgUrl.push(val.path)
						})
					}
				})
			},
			// 确定上传图片，传到服务器
			submitImg() {
				console.log(this.contentText)
				console.log(this.preImgUrl)
				// console.log(this.dateFormat(this.date))
				// uni.navigateBack({
				//     delta: 1
				// });
				// 如果没有选择图片则返回，本次需求没有此规则，故注释掉

				if (this.preImgUrl.length == 0) {
					uni.showToast({
						icon: 'none',
						title: '请选择图片'
					})
					return
				}
				// 获取图片地址的数量，用于实现同步请求
				let len = this.preImgUrl.length
				// 创建变量，用来创建定时器，用于实现同步请求
				let timer = null
				//阻塞阈值，因为使用定时器实现同步，所以需要防止无限循环，用于实现同步请求
				let threshold = 3000;
				let a = '';
				// 遍历要上传的图片临时地址，进行上传
				this.preImgUrl.map(val => {
					uni.uploadFile({
						url: "https://www.smacaftersales.com:443/workOrder/workOrder/fileUpload", //服务器地址
						filePath: val, //存在本地要上传的临时图片地址
						name: 'file', //名字可以随便写
						success(res) { //上传成功的回调函数
							console.log(res.data)
							//console.log(res, '上传图片成功')
							a += res.data + ","
							console.log(a)
						},
						complete: (X) => {
							// 不论success还是fail，都把len-1
							len--;
						},
						fail(res) {
							console.log(res, '上传失败')
							uni.showToast({
								icon: 'none',
								title: '上传失败'
							})
						}
					})
				})
				// 关键部分
				// 通过此部分来延续方法的时长，待到异步的回调执行完毕后则关闭
				// 以防万一，建议设定一个阈值，防止出现意外导致无限循环
				timer = setInterval(() => {
					threshold--;
					console.log(threshold);
					console.log(this.item)
					// 只要len结束，将定时器清除
					if (!len || threshold == 0) {
						console.log("同步结束")
						// 上传操作完成，消除阻塞
						clearInterval(timer)
						uni.request({
							url: "https://www.smacaftersales.com:443/workOrder/workOrder/Upload8D",
							// url: "http://192.168.3.7:8080/workOrder/workOrder/Upload8D",
							method: "POST",
							data: {
								workid: this.item.workid,
								afterSales8DForm: a,
							},
							header: {
								// "Content-type": "application/x-www-form-urlencoded",
								"Content-type": "application/json",
								// "Content-type": "multipart/form-data"
								// "Content-type": "text/xml"
							},
							success: (res) => {
								if (res.data.data == 1) {
									uni.showToast({
										title: "8D单上报成功",
										duration: 2000,
										icon: 'success'
									})
									this.timer = setTimeout(() => {
										this.backPageRefresh(2) // 或者 this.backPageRefresh(n)
									}, 2000)
								} else {
									uni.showToast({
										title: '出现错误，请重新上传！',
										icon: 'error',
										duration: 2000
									})
								}
							},
						});
					}
					// 这个参数一定要写，如果不写在IOS端会报错导致同步失败
				}, 1)

			},
			backPageRefresh(page) { // page这个值如果你只返回上一页可以不用传，返回上上页就传2，以此类推
				let pages = getCurrentPages(); // 当前页面
				let i = 0
				if (page) {
					i = page - 1
				}
				let beforePage = pages[pages.length - (2 +
					i)]; // 前一个页面或者更多  beforePage 这个值当你刷新浏览器后是无法返回的，需要用到浏览器历史记录返回上一页 history.back()
				if (beforePage && beforePage.$vm.refreshRequest) {
					uni.navigateBack({
						delta: page || 1,
						success: function() {
							beforePage.$vm.refreshRequest(); // 执行前一个页面或者前几个页面并且刷新该页面
						}
					});
				} else {
					history.back() // 浏览器的方法返回上一页
				}
			},
			//获取当前时间
			dateFormat(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				// 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
				let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				// 拼接
				return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
				// return year + "-" + month + "-" + day;
			},
			//删除某张图片，从本地的临时路径图片中, 删除路径即可
			delImg(index) {
				this.imgNum--;
				this.preImgUrl.splice(index, 1)
				if (this.imgNum < 3) {
					this.isShowAddImgBtn = true;
				}
			},
			bindTextAreaBlur: function(e) {
				console.log(e.detail.value)
			},
			changeRadio1() {
				//如果是之前确认过，但是没点击编辑按钮，则直接return
				if (this.addoredit == 'edit' && this.editclick == 0) {
					return
				}
				this.radio1 = 1;
				console.log("是")
			},
			changeRadio2() {
				//如果是之前确认过，但是没点击编辑按钮，则直接return
				if (this.addoredit == 'edit' && this.editclick == 0) {
					return
				}
				this.radio1 = 2;
				console.log("否")
			},
			//点击小图查看大图片
			showImg(val, index) {
				console.log(val, '点击了')
				let that = this
				uni.previewImage({
					// 对选中的图片进行预览
					urls: that.preImgUrl, //图片数组  // urls:['','']  图片的地址 是数组形式
					current: index, //当前图片的下标
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	* {
		box-sizing: border-box;
	}

	.qtpicker {
		width: 100%;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		margin: 0 auto;
		padding: 10rpx 0;

		.preImgs {
			margin: 13rpx;
			position: relative;

			image {
				width: 200rpx;
				height: 200rpx;
			}

			.cuo {
				width: 17pt;
				height: 17pt;
				//line-height: 12px;
				//text-align: center;
				///* font-size: 16px; */
				//border-radius: 50%;
				//background-color: #223E4B;
				//color: #FFFFFF;
				position: absolute;
				right: 0px;
				top: 0px;
			}
		}


		.addImg {
			width: 200rpx;
			height: 200rpx;
			border: 2rpx solid #d4d4d4;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			font-size: 20rpx;
			background-color: #e2dddd;
			margin-left: 13rpx;
			margin-top: 13rpx;
		}
	}

	.cell {
		height: auto;
		padding-left: 20rpx;
		padding-right: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: flex-start;
		background: #fff;
		//border-bottom: 1px solid #BDD8F6;

		.cell-left {
			display: flex;
			align-items: center;
			padding: 8px;

			.cell-icon {
				width: 50rpx;
				height: 50rpx;
			}

			.cell-text {
				color: #595959;
				font-size: 15px;
				margin-left: 0rpx;

				//width: 180rpx;
			}
		}

		.iconfont {
			font-size: 40rpx;
			color: #999;
		}
	}

	.radio-content {
		height: 40rpx;
		display: flex;
		align-items: center;
	}

	.radio {
		width: 24rpx;
		height: 24rpx;
		border-radius: 50%;
		border: 1rpx solid #CCCCCC;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin: 0rpx 26rpx 0rpx 15rpx;
	}

	.radio-active {
		width: 10rpx;
		height: 10rpx;
		border-radius: 50%;
		background-color: #0079FC;
	}

	.radio-default {
		border: 2rpx solid #0079FC;
	}

	.radio-right {
		margin-left: 36rpx;
	}
</style>